<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <style>
    html,body{margin: 0;padding:0;}
    .cont{width: 1000px;overflow: hidden;}
    .cont .box{float: left;border: solid 1px black;width: 250px;box-sizing: border-box;text-align: center;}
    .cont .box img{width: 70%;height:150px}
    .cont .box p{line-height: 20px;height:40px;overflow: hidden;}
  </style>
</head>
<body>
  <div class="cont"></div>
  <div class="detail"></div>
</body>
<script>

  const cont = document.querySelector(".cont")
  const detail = document.querySelector(".detail")

  const url = "http://10.11.50.46:3000/getgoods";

  ajax(url).then(res=>{
    res = JSON.parse(res).data;
    const arr = [];
    for(let i=0;i<4;i++){
      arr.push(res[random(0, res.length-1)])
    }
    
    let str = "";
    arr.forEach(val=>{
      str += `<div class="box">
                <span class="goodsBox" data-id="${val.goodsId}">
                  <img src="${val.goodsImg}" alt="">
                  <p>${val.goodsName}</p>
                  <p>${val.price}</p>
                </span>
                <input type="button" value="加购物车" data-id="${val.goodsId}">
              </div>`;
    })
    cont.innerHTML = str;

    cont.querySelectorAll(".goodsBox").forEach(val=>{
      val.onclick = function(){
        ajax(url, {
          id: this.dataset.id
        }).then((res)=>{
          res = JSON.parse(res).data[0];
          let str = `<div class="imgbox">
                        <img src="${res.goodsImg}" alt="">
                      </div>
                      <div class="detail">
                        <h3>名称：${res.goodsName}</h3>
                        <p>详细描述：${res.message}</p>
                        <p>价格：${res.price}</p>
                        <p>品牌：${res.brand}</p>
                        <p>分类：${res.kind}</p>
                      </div>;`
              detail.innerHTML = str
        })
      }
    })
  });


  // ajax(url).then(res=>{
  //   return ajax(url, {
  //     id: res[0].goodsId
  //   })
  // }).then(res=>{
  //   console.log(res);
  // });
  

  function ajax(url, data={}){
    let str = "";
    for(let i in data){
      str += `${i}=${data[i]}&`
    }
    url += "?" + str.slice(0,-1);

    const xhr = new XMLHttpRequest();
    xhr.open("get", url);
    xhr.send();
    return new Promise((resolve, reject)=>{
      xhr.onload = function(){
        if(xhr.status === 200){
          resolve(xhr.responseText);
        }else{
          reject(xhr.status);
        }
      }
    })
  }


  function random(a,b){
    return Math.round(Math.random()*(a-b)+b)
  }
</script>
</html>